﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Org.BouncyCastle.Asn1.X509;
using RearLivestock.Beginning.Api.Application.Command.ChangeHouse;
using RearLivestock.Common.Domains.hhx;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.Condition
{
    public class GetConditionHandler : IRequestHandler<GetConditionCommand, Result<PageResultDto<ConditionDto>>>
    {
        /// <summary>
        /// 品相测定仓储
        /// </summary>
        private readonly IBaseRepository<Conditions> conditionsRepository;
        /// <summary>
        /// 基本信息耳号仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> basicInformationRepository;
        /// <summary>
        /// 栋舍信息仓储
        /// </summary>
        private readonly IBaseRepository<Bedrooms> bedroomsRepository;
        /// <summary>
        ///  栏位仓储
        /// </summary>
        private readonly IBaseRepository<Fields> fieldsRepository;
        /// <summary>
        /// 品种
        /// </summary>
        private readonly IBaseRepository<Varieties> varietiesRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<AddChangeHouseHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="conditionsRepository"></param>
        /// <param name="basicInformationRepository"></param>
        /// <param name="bedroomsRepository"></param>
        /// <param name="fieldsRepository"></param>
        /// <param name="varietiesRepository"></param>
        /// <param name="logger"></param>
        public GetConditionHandler(IBaseRepository<Conditions> conditionsRepository, IBaseRepository<BasicInformation> basicInformationRepository, IBaseRepository<Bedrooms> bedroomsRepository, IBaseRepository<Fields> fieldsRepository, IBaseRepository<Varieties> varietiesRepository, ILogger<AddChangeHouseHandler> logger)
        {
            this.conditionsRepository = conditionsRepository;
            this.basicInformationRepository = basicInformationRepository;
            this.bedroomsRepository = bedroomsRepository;
            this.fieldsRepository = fieldsRepository;
            this.varietiesRepository = varietiesRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<ConditionDto>>> Handle(GetConditionCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<ConditionDto>>() { Code = (int)CommonErrorCode.Search, Data = new PageResultDto<ConditionDto>() };
            var page = new PageResultDto<ConditionDto>() { TotalCount = 0, PageCount = 0, List = new List<ConditionDto>() };
            try
            {
                var list = await(from a in await conditionsRepository.GetAll()
                                 join b in await basicInformationRepository.GetAll()
                                 on a.BasicInforId equals b.BasicInforId
                                 join c in await varietiesRepository.GetAll()
                                 on b.VarietiesId equals c.VarietiesId
                                 join d in await bedroomsRepository.GetAll()
                                 on b.BedroomId equals d.BedroomId
                                 join e in await fieldsRepository.GetAll()
                                 on b.FieldId equals e.FieldId
                                 select new ConditionDto()
                                 {
                                     ConditionId=a.ConditionId,
                                     ConditionDate = a.ConditionDate,
                                     BasicInforId=a.BasicInforId,
                                     Occlusion = a.Occlusion,
                                     Hair = a.Hair,
                                     Spot = a.Spot,
                                     HoofColor = a.HoofColor,
                                     MouthColor = a.MouthColor,
                                     PigEar = a.PigEar,
                                     FatDistribution = a.FatDistribution,
                                     EarNumber = b.EarNumber,
                                     Gender = b.Gender,
                                     VarietiesId = c.VarietiesId,
                                     VarietiesName =c.VarietiesName,
                                     BedroomId = d.BedroomId,
                                     BedroomName = d.BedroomName,
                                     FieldId = e.FieldId,
                                     FieldName = e.FieldName,
                                     CreatedOwner = a.CreatedOwner,
                                     CreatedTime = a.CreatedTime,
                                     UpdateOwner = a.UpdateOwner,
                                     UpdateTime = a.UpdateTime,
                                     ExamineOwner = a.ExamineOwner,
                                     ExamineTime = a.ExamineTime,
                                 }).ToListAsync();
                //耳号查询
                if (request.BasicInforId != 0)
                {
                    list = list.Where(d => d.BasicInforId == request.BasicInforId).ToList();
                }
                //品种查询
                if (request.VarietiesId != 0)
                {
                    list = list.Where(d => d.VarietiesId == request.VarietiesId).ToList();
                }
                //性别查询
                if (request.Gender != 0)
                {
                    list = list.Where(d => d.Gender == request.Gender).ToList();
                }
                //总条数
                page.TotalCount = list.Count();
                page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.pageSize);
                page.List = list.OrderBy(d => d.ConditionId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
                result.Data = page;
                result.Code = (int)CommonErrorCode.Success;
                result.Msg = "品相测定列表显示成功";
            }
            catch (Exception)
            {
                result.Msg = "品相测定列表显示异常";
                logger.LogError("品相测定列表显示异常");
            }
            return result;
        }
    }
}
